package com.kelai.service.impl;

import com.kelai.common.InfoPage;
import com.kelai.common.PageInfo;
import com.kelai.common.constants.WebAppConstants;
import com.kelai.domain.CustomerEntity;
import com.kelai.domain.DeviceDataDayEntity;
import com.kelai.domain.DeviceEntity;
import com.kelai.repository.ICustomerRepository;
import com.kelai.repository.IDeviceRepository;
import com.kelai.service.IDeviceDayService;
import com.kelai.utils.BreezeeUtils;
import com.kelai.utils.ContextUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.olap4j.*;
import org.olap4j.metadata.Member;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.sql.DriverManager;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 设备日统计服务
 * Created by Luffy on 2017/04/21.
 */
@Service("deviceDayService")
public class DefaultDeviceDayService implements IDeviceDayService {
    private final static Logger logger = LoggerFactory.getLogger(DefaultDeviceDayService.class);
    private final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private final ICustomerRepository customerRepository;

    private final JdbcTemplate jdbcTemplate;

    @Autowired
    public DefaultDeviceDayService(ICustomerRepository customerRepository, JdbcTemplate jdbcTemplate) {
        this.customerRepository = customerRepository;
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public List<DeviceDataDayEntity> listAll(Map condition) {

        PageInfo pageInfo = new PageInfo(condition);
        if (condition.get("_sort") != null) {
            pageInfo.setSort((Sort) condition.get("_sort"));
        } else {
            pageInfo.setSort(new Sort(Sort.Direction.ASC, "rowNum","id"));
        }

        List<DeviceDataDayEntity> l = new ArrayList<>();
        try {
            ICustomerRepository customerRepository = ContextUtil.getBean("customerRepository", ICustomerRepository.class);
            IDeviceRepository deviceRepository = ContextUtil.getBean("deviceRepository", IDeviceRepository.class);
            System.out.println("----");
            Class.forName("org.olap4j.driver.xmla.XmlaOlap4jDriver");
            OlapConnection con = (OlapConnection) DriverManager.getConnection("jdbc:xmla:Server=http://"+WebAppConstants.BI_LINK_IP+"/MDKL/msmdpump.dll;Catalog="+ WebAppConstants.BI_LINK_NAME);
            OlapWrapper wrapper = (OlapWrapper) con;
            OlapConnection olapConnection = wrapper.unwrap(OlapConnection.class);
            OlapStatement stmt = olapConnection.createStatement();

            StringBuffer strPageBuffer = new StringBuffer();
            strPageBuffer.append(" ");
            strPageBuffer.append(" SELECT NON EMPTY { [Measures].[进], [Measures].[出] } ON 0, ");
            strPageBuffer.append(" {  [设备].[设备ID].[设备ID].ALLMEMBERS *  ");
            strPageBuffer.append(" [时间].[年].[年].ALLMEMBERS * ");
            strPageBuffer.append(" [时间].[月].[月].ALLMEMBERS *  ");
            strPageBuffer.append(" [时间].[日].[日].ALLMEMBERS } on 1 ");
            strPageBuffer.append(" FROM ( SELECT ( { [时间].[年月日小时].[日].&["+condition.get("_startDate")+"T00:00:00]:[时间].[年月日小时].[日].&["+condition.get("_endDate")+"T00:00:00] }, {");

            if(condition.get("_deviceIds") != null && CollectionUtils.isNotEmpty((List<String>)condition.get("_deviceIds"))){
                ((List<String>)condition.get("_deviceIds")).stream().forEach( deviceId -> {
                    strPageBuffer.append("  [设备].[设备ID].[设备ID].&["+deviceId+"] , ");
                });
                strPageBuffer.append("  [设备].[设备ID].[设备ID].&[-1] ");
            }else{
                strPageBuffer.append(" [设备].[设备ID].[设备ID].&["+condition.get("device_id_obj_ae")+"]  ");
            }

            strPageBuffer.append(" } ) ON COLUMNS ");
            strPageBuffer.append(" FROM [客流]) ");

            System.out.println(strPageBuffer);
            System.out.println("=================================================");
            CellSet cellSet = stmt.executeOlapQuery(strPageBuffer.toString());

            for (Position rowPos : cellSet.getAxes().get(1)) {
                String s = "";
                for (Member member : rowPos.getMembers()) {
                    s += member.getCaption() + "*";
                }
                for (Position colPos : cellSet.getAxes().get(0)) {
                    Cell cell = cellSet.getCell(colPos, rowPos);
                    s += cell.getFormattedValue() + "*";
                }
                String[] ss = s.split("\\*");
                String id = ss[0] + "-" + ss[1] + ss[2] + ss[3];
                DeviceDataDayEntity sdde = new DeviceDataDayEntity();
                sdde.setId(id);
                sdde.setCode(id);

                DeviceEntity de = deviceRepository.findOne(ss[0]);
                if (de == null)
                    continue;
                CustomerEntity ce = de.getCustomer();
                if (ce == null) {
                    System.out.println("device : "+de.getCode() +" no customer");
                    continue;
                }
                sdde.setCustomer(ce);
                sdde.setCustomerId(ce.getParentId());
                sdde.setDevice(de);
                try{
                    sdde.setHappenTime(BreezeeUtils.str2Date(ss[1] + "-" + ss[2] + "-" + ss[3]));
                }catch(Exception e){
                    logger.info(e.getMessage()+" "+ss[1] + "-" + ss[2] + "-" + ss[3]);
                    sdde.setHappenTime(BreezeeUtils.str2Date("1970-01-01"));
                }
                sdde.setYear(Integer.parseInt(ss[1]));
                if(ss.length < 5){
                    sdde.setDxin(0);
                    sdde.setDxout(0);
                }else{
                    sdde.setDxin(Integer.parseInt(ss[4]));
                    sdde.setDxout(Integer.parseInt(ss[5]));
                }
                l.add(sdde);
            }

        } catch (Exception e1) {
            e1.printStackTrace();
        }

        return l;
    }

    @Override
    public InfoPage<DeviceDataDayEntity> pageAll(Map condition) {
        PageInfo pageInfo = new PageInfo(condition);
        if (condition.get("_sort") != null) {
            pageInfo.setSort((Sort) condition.get("_sort"));
        } else {
            pageInfo.setSort(new Sort(Sort.Direction.ASC, "rowNum","id"));
        }

        List<DeviceDataDayEntity> l = new ArrayList<>();
        String cnt = "0";
        try {
            ICustomerRepository customerRepository = ContextUtil.getBean("customerRepository", ICustomerRepository.class);
            IDeviceRepository deviceRepository = ContextUtil.getBean("deviceRepository", IDeviceRepository.class);
            System.out.println("----");
            Class.forName("org.olap4j.driver.xmla.XmlaOlap4jDriver");
            OlapConnection con = (OlapConnection) DriverManager.getConnection("jdbc:xmla:Server=http://"+WebAppConstants.BI_LINK_IP+"/MDKL/msmdpump.dll;Catalog="+WebAppConstants.BI_LINK_NAME);
            OlapWrapper wrapper = (OlapWrapper) con;
            OlapConnection olapConnection = wrapper.unwrap(OlapConnection.class);
            OlapStatement stmt = olapConnection.createStatement();

            Integer pageStart = Integer.parseInt(condition.get("pageNumber").toString())*
                    Integer.parseInt(condition.get("pageSize").toString());

            StringBuffer strPageBuffer = new StringBuffer();
            strPageBuffer.append(" ");
            strPageBuffer.append(" SELECT NON EMPTY { [Measures].[进], [Measures].[出] } ON 0, ");
            strPageBuffer.append("  {  subset ");
            strPageBuffer.append(" (( ");
            strPageBuffer.append(" [设备].[设备ID].[设备ID].ALLMEMBERS *  ");
            strPageBuffer.append(" [时间].[年].[年].ALLMEMBERS * ");
            strPageBuffer.append(" [时间].[月].[月].ALLMEMBERS *  ");
            strPageBuffer.append(" [时间].[日].[日].ALLMEMBERS ) ");
            strPageBuffer.append(" ,"+pageStart+" ,"+condition.get("pageSize")+")} on 1 ");
            strPageBuffer.append(" FROM ( SELECT ( { [时间].[年月日小时].[日].&["+condition.get("_startDate")+"T00:00:00]:[时间].[年月日小时].[日].&["+condition.get("_endDate")+"T00:00:00] }, {");

            if(condition.get("_deviceIds") != null && CollectionUtils.isNotEmpty((List<String>)condition.get("_deviceIds"))){
                ((List<String>)condition.get("_deviceIds")).stream().forEach( deviceId -> {
                    strPageBuffer.append("  [设备].[设备ID].[设备ID].&["+deviceId+"] , ");
                });
                strPageBuffer.append("  [设备].[设备ID].[设备ID].&[-1] ");
            }else{
                strPageBuffer.append(" [设备].[设备ID].[设备ID].&["+condition.get("device_id_obj_ae")+"]  ");
            }

            strPageBuffer.append(" } ) ON COLUMNS ");
            strPageBuffer.append(" FROM [客流]) ");

            CellSet cellSet = stmt.executeOlapQuery(strPageBuffer.toString());

            for (Position rowPos : cellSet.getAxes().get(1)) {
                String s = "";
                for (Member member : rowPos.getMembers()) {
                    s += member.getCaption() + "*";
                }
                for (Position colPos : cellSet.getAxes().get(0)) {
                    Cell cell = cellSet.getCell(colPos, rowPos);
                    s += cell.getFormattedValue() + "*";
                }
                String[] ss = s.split("\\*");
                String id = ss[0] + "-" + ss[1] + ss[2] + ss[3];
                DeviceDataDayEntity sdde = new DeviceDataDayEntity();
                sdde.setId(id);
                sdde.setCode(id);
                DeviceEntity de = deviceRepository.findOne(ss[0]);
                if (de == null)
                    continue;
                CustomerEntity ce = de.getCustomer();
                if (ce == null) {
                    System.out.println("device : "+de.getCode() +" no customer");
                    continue;
                }
                sdde.setCustomer(ce);
                sdde.setCustomerId(ce.getParentId());
                sdde.setDevice(de);
                try{
                    sdde.setHappenTime(BreezeeUtils.str2Date(ss[1] + "-" + ss[2] + "-" + ss[3]));
                }catch(Exception e){
                    logger.info(e.getMessage()+" "+ss[1] + "-" + ss[2] + "-" + ss[3]);
                    sdde.setHappenTime(BreezeeUtils.str2Date("1970-01-01"));
                }
                sdde.setYear(Integer.parseInt(ss[1]));
                if(ss.length < 5){
                    sdde.setDxin(0);
                    sdde.setDxout(0);
                }else{
                    sdde.setDxin(Integer.parseInt(ss[4]));
                    sdde.setDxout(Integer.parseInt(ss[5]));
                }
                l.add(sdde);
            }

        StringBuffer strCntBuffer = new StringBuffer();
        strCntBuffer.append(" ");
        strCntBuffer.append(" WITH ");
        strCntBuffer.append(" SET [xx] as  ({[设备].[设备ID].[设备ID].ALLMEMBERS * [时间].[年].[年].ALLMEMBERS * [时间].[月].[月].ALLMEMBERS *[时间].[日].[日].ALLMEMBERS* [Measures].[进]}) ");
        strCntBuffer.append(" MEMBER [Measures].[X] AS count([xx]) ");
        strCntBuffer.append(" SELECT Measures.X ON 0 ");
        strCntBuffer.append(" FROM ( SELECT ( { [时间].[年月日小时].[日].&["+condition.get("_startDate")+"T00:00:00]:[时间].[年月日小时].[日].&["+condition.get("_endDate")+"T00:00:00] }, {");

            if(condition.get("_deviceIds") != null && CollectionUtils.isNotEmpty((List<String>)condition.get("_deviceIds"))){
                ((List<String>)condition.get("_deviceIds")).stream().forEach( deviceId -> {
                    strCntBuffer.append("  [设备].[设备ID].[设备ID].&["+deviceId+"] , ");
                });
                strCntBuffer.append("  [设备].[设备ID].[设备ID].&[-1] ");
            }else{
                strCntBuffer.append(" [设备].[设备ID].[设备ID].&["+condition.get("device_id_obj_ae")+"]  ");
            }

        strCntBuffer.append("  } ) ON COLUMNS ");
        strCntBuffer.append(" FROM [客流]) ");

        CellSet cellSetCnt = stmt.executeOlapQuery(strCntBuffer.toString());

        for (Position rowPos : cellSetCnt.getAxes().get(0)) {
            Cell cell = cellSetCnt.getCell(rowPos);
            cnt = cell.getFormattedValue();
        }
    } catch (Exception e1) {
        e1.printStackTrace();
    }

        return new InfoPage<DeviceDataDayEntity>(l,new Long(cnt));
    }
}
